<template>
  <div class="ai-assistant-page">
    <div class="page-container">
      <!-- 页面头部 -->
      <div class="page-header">
        <h1>AI剪纸助手</h1>
        <p>智能剪纸助手为您解答剪纸相关问题</p>
      </div>

      <!-- 主内容区域 -->
      <div class="main-wrapper">
        <!-- 左侧历史记录 -->
        <div class="history-sidebar">
          <div class="sidebar-header">
            <h3>对话历史</h3>
            <el-button type="primary" size="small" @click="createNewConversation" :icon="Plus">
              新对话
            </el-button>
          </div>
          
          <div class="conversation-list">
            <div
              v-for="conv in conversations"
              :key="conv.id"
              class="conversation-item"
              :class="{ active: currentConversationId === conv.id }"
              @click="switchConversation(conv.id)"
            >
              <div class="conversation-info">
                <div class="conversation-title">{{ conv.title }}</div>
                <div class="conversation-time">{{ formatTime(conv.updateTime) }}</div>
                <div class="conversation-preview">{{ conv.preview }}</div>
              </div>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                circle
                @click.stop="deleteConversation(conv.id)"
                class="delete-btn"
              />
            </div>
            
            <div v-if="conversations.length === 0" class="empty-history">
              <el-icon :size="48"><ChatDotRound /></el-icon>
              <p>暂无对话记录</p>
            </div>
          </div>
        </div>

        <!-- 聊天区域 -->
        <div class="chat-container">
        <!-- 消息列表 -->
        <div class="message-list" ref="messageListRef">
          <!-- 欢迎消息 -->
          <div class="message-item assistant" v-if="messages.length === 0">
            <div class="message-avatar">
              <el-icon :size="24"><ChatDotRound /></el-icon>
            </div>
            <div class="message-content">
              <div class="message-text">
                您好！我是AI剪纸助手，很高兴为您服务。您可以向我咨询：
                <ul>
                  <li>剪纸的历史文化背景</li>
                  <li>各种剪纸技法和技巧</li>
                  <li>剪纸作品创作建议</li>
                  <li>剪纸工具和材料选择</li>
                  <li>剪纸教学和学习方法</li>
                </ul>
                请输入您的问题，我会尽力为您解答！
              </div>
            </div>
          </div>

          <!-- 聊天消息 -->
          <div
            v-for="(message, index) in messages"
            :key="index"
            class="message-item"
            :class="message.role"
          >
            <div class="message-avatar">
              <el-icon v-if="message.role === 'assistant'" :size="24"><ChatDotRound /></el-icon>
              <el-avatar v-else :src="userStore.userAvatar" :size="32">
                <User />
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(message.content)"></div>
              <div class="message-time">{{ message.timestamp }}</div>
            </div>
          </div>

          <!-- 加载中提示（仅在没有正在生成的消息时显示） -->
          <div v-if="isLoading && messages.length > 0 && messages[messages.length - 1].role === 'user'" class="message-item assistant">
            <div class="message-avatar">
              <el-icon :size="24"><ChatDotRound /></el-icon>
            </div>
            <div class="message-content">
              <div class="message-text loading-text">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-container">
          <div class="input-wrapper">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              placeholder="请输入您的问题..."
              @keydown.enter.exact.prevent="handleSend"
              :disabled="isLoading"
              resize="none"
            />
            <div class="input-actions">
              <div class="input-tips">
                <span>按 Enter 发送，Shift + Enter 换行</span>
              </div>
              <el-button
                type="primary"
                @click="handleSend"
                :disabled="!inputMessage.trim() || isLoading"
                :loading="isLoading"
              >
                发送
              </el-button>
            </div>
          </div>
        </div>
        </div>
      </div>

      <!-- 快捷提问 -->
      <div class="quick-questions" v-if="messages.length === 0 && currentConversationId">
        <h3>快捷提问</h3>
        <div class="question-grid">
          <div
            v-for="(question, index) in quickQuestions"
            :key="index"
            class="question-card"
            @click="handleQuickQuestion(question)"
          >
            <el-icon><ChatLineRound /></el-icon>
            <span>{{ question }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ChatDotRound, User, ChatLineRound, Plus, Delete } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { aiApi } from '@/api/ai'

const userStore = useUserStore()

interface Message {
  role: 'user' | 'assistant'
  content: string
  timestamp: string
}

interface Conversation {
  id: string
  title: string
  preview: string
  messages: Message[]
  createTime: string
  updateTime: string
}

// 响应式数据
const messages = ref<Message[]>([])
const inputMessage = ref('')
const isLoading = ref(false)
const messageListRef = ref<HTMLElement>()
const conversations = ref<Conversation[]>([])
const currentConversationId = ref<string>('')

// 本地存储键名
const STORAGE_KEY = 'ai_conversations'

// 快捷提问
const quickQuestions = [
  '剪纸的历史起源是什么？',
  '剪纸有哪些基本技法？',
  '初学者如何开始学习剪纸？',
  '剪纸需要哪些工具和材料？',
  '如何创作对称剪纸作品？',
  '剪纸在中国文化中有什么意义？'
]

// 格式化消息内容（支持简单的markdown）
const formatMessage = (content: string) => {
  if (!content) return ''
  
  // 转换换行符
  let formatted = content.replace(/\n/g, '<br>')
  
  // 转换无序列表（匹配 - 或 * 开头）
  formatted = formatted.replace(/^[•\-\*]\s+(.+)$/gm, '<li>$1</li>')
  
  // 转换有序列表
  formatted = formatted.replace(/^\d+\.\s+(.+)$/gm, '<li>$1</li>')
  
  // 包裹列表项
  formatted = formatted.replace(/(<li>[\s\S]+?<\/li>)/g, (match) => {
    if (!match.includes('<ul>') && !match.includes('<ol>')) {
      return '<ul>' + match + '</ul>'
    }
    return match
  })
  
  // 转换粗体
  formatted = formatted.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
  
  // 转换代码块
  formatted = formatted.replace(/```([\s\S]+?)```/g, '<pre><code>$1</code></pre>')
  
  // 转换行内代码
  formatted = formatted.replace(/`([^`]+?)`/g, '<code>$1</code>')
  
  return formatted
}

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  })
}

// 发送消息（使用流式响应）
const handleSend = async () => {
  if (!inputMessage.value.trim() || isLoading.value) {
    return
  }

  const userMessage = inputMessage.value.trim()
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: userMessage,
    timestamp: getCurrentTime()
  })
  
  inputMessage.value = ''
  scrollToBottom()
  
  // 调用流式AI接口
  isLoading.value = true
  
  // 创建AI消息占位符
  const aiMessageIndex = messages.value.length
  messages.value.push({
    role: 'assistant',
    content: '',
    timestamp: getCurrentTime()
  })
  
  try {
    // 使用fetch实现SSE流式接收
    const response = await fetch('/api/ai/stream-chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: userMessage,
        history: messages.value.slice(0, -2).map(m => ({
          role: m.role,
          content: m.content
        }))
      })
    })
    
    if (!response.ok) {
      throw new Error('网络请求失败')
    }
    
    const reader = response.body?.getReader()
    const decoder = new TextDecoder('utf-8')
    
    if (!reader) {
      throw new Error('无法读取响应流')
    }
    
    let buffer = ''
    let currentEvent = ''
    
    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        isLoading.value = false
        break
      }
      
      // 解码数据
      buffer += decoder.decode(value, { stream: true })
      
      // 按行分割
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''  // 保留最后不完整的行
      
      for (const line of lines) {
        const trimmedLine = line.trim()
        
        if (!trimmedLine) {
          continue  // 跳过空行
        }
        
        if (trimmedLine.startsWith('event:')) {
          currentEvent = trimmedLine.substring(6).trim()
        } else if (trimmedLine.startsWith('data:')) {
          const data = trimmedLine.substring(5).trim()
          
          if (currentEvent === 'done' || data === '[DONE]') {
            isLoading.value = false
            continue
          }
          
          if (currentEvent === 'error') {
            ElMessage.error(data)
            continue
          }
          
          // 默认是消息数据
          if (data && currentEvent === 'message') {
            if (messages.value[aiMessageIndex]) {
              messages.value[aiMessageIndex].content += data
              scrollToBottom()
            }
          }
          // 如果没有事件类型，也尝试添加（兼容处理）
          else if (data && !currentEvent && data !== '[DONE]') {
            if (messages.value[aiMessageIndex]) {
              messages.value[aiMessageIndex].content += data
              scrollToBottom()
            }
          }
          
          currentEvent = ''  // 重置事件类型
        }
      }
    }
    
    scrollToBottom()
  } catch (error: any) {
    // 如果出错，移除空的AI消息
    if (messages.value[aiMessageIndex] && !messages.value[aiMessageIndex].content) {
      messages.value.splice(aiMessageIndex, 1)
    }
    ElMessage.error(error.message || '发送失败，请稍后重试')
    console.error('AI聊天错误:', error)
  } finally {
    isLoading.value = false
  }
}

// 快捷提问
const handleQuickQuestion = (question: string) => {
  inputMessage.value = question
  handleSend()
}

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 今天
  if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  
  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.getDate() === yesterday.getDate()) {
    return '昨天'
  }
  
  // 本周
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    return days[date.getDay()]
  }
  
  // 更早
  return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
}

// 加载历史会话
const loadConversations = () => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored) {
      conversations.value = JSON.parse(stored)
    }
  } catch (error) {
    console.error('加载历史会话失败:', error)
  }
}

// 保存会话到本地存储
const saveConversations = () => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(conversations.value))
  } catch (error) {
    console.error('保存会话失败:', error)
  }
}

// 创建新对话
const createNewConversation = () => {
  const newConv: Conversation = {
    id: generateId(),
    title: '新对话',
    preview: '开始新的对话...',
    messages: [],
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString()
  }
  
  // 新对话添加到列表开头
  conversations.value.unshift(newConv)
  currentConversationId.value = newConv.id
  messages.value = []
  saveConversations()
}

// 切换对话
const switchConversation = (conversationId: string) => {
  const conv = conversations.value.find(c => c.id === conversationId)
  if (conv) {
    currentConversationId.value = conversationId
    messages.value = [...conv.messages]
    scrollToBottom()
  }
}

// 删除对话
const deleteConversation = async (conversationId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？', '确认删除', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    conversations.value = conversations.value.filter(c => c.id !== conversationId)
    
    // 如果删除的是当前对话，切换到第一个或创建新对话
    if (currentConversationId.value === conversationId) {
      if (conversations.value.length > 0) {
        switchConversation(conversations.value[0].id)
      } else {
        createNewConversation()
      }
    }
    
    saveConversations()
    ElMessage.success('对话已删除')
  } catch {
    // 用户取消删除
  }
}

// 更新当前对话
const updateCurrentConversation = () => {
  const conv = conversations.value.find(c => c.id === currentConversationId.value)
  if (conv) {
    conv.messages = [...messages.value]
    conv.updateTime = new Date().toISOString()
    
    // 更新标题和预览
    if (messages.value.length > 0) {
      const firstUserMsg = messages.value.find(m => m.role === 'user')
      if (firstUserMsg) {
        conv.title = firstUserMsg.content.substring(0, 20) + (firstUserMsg.content.length > 20 ? '...' : '')
        const lastMsg = messages.value[messages.value.length - 1]
        conv.preview = lastMsg.content.substring(0, 30) + (lastMsg.content.length > 30 ? '...' : '')
      }
    }
    
    // 不再移动对话到列表最前面，保持固定顺序
    
    saveConversations()
  }
}

// 监听消息变化，自动保存
watch(messages, () => {
  if (currentConversationId.value) {
    updateCurrentConversation()
  }
}, { deep: true })

// 初始化
onMounted(() => {
  loadConversations()
  
  // 如果没有对话，创建一个新对话
  if (conversations.value.length === 0) {
    createNewConversation()
  } else {
    // 加载第一个对话
    switchConversation(conversations.value[0].id)
  }
  
  scrollToBottom()
})
</script>

<style scoped>
.ai-assistant-page {
  min-height: calc(100vh - 64px);
  background: #f5f5f5;
  padding: 24px 0;
}

.page-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 页面头部 */
.page-header {
  text-align: center;
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #666;
}

/* 主内容区域 */
.main-wrapper {
  display: flex;
  gap: 20px;
  height: 600px;
}

/* 左侧历史记录 */
.history-sidebar {
  width: 280px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.conversation-item {
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #e0e0e0;
  position: relative;
}

.conversation-item:hover {
  background: #f5f5f5;
  border-color: #d32f2f;
}

.conversation-item.active {
  background: #fff5f5;
  border-color: #d32f2f;
}

.conversation-info {
  padding-right: 30px;
}

.conversation-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.conversation-preview {
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.delete-btn {
  position: absolute;
  top: 50%;
  right: 8px;
  transform: translateY(-50%);
  opacity: 0;
  transition: opacity 0.3s;
}

.conversation-item:hover .delete-btn {
  opacity: 1;
}

.empty-history {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  padding: 40px 20px;
}

.empty-history .el-icon {
  color: #d0d0d0;
  margin-bottom: 16px;
}

.empty-history p {
  font-size: 14px;
}

/* 聊天容器 */
.chat-container {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 消息列表 */
.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-item {
  display: flex;
  gap: 12px;
  animation: fadeInUp 0.3s ease;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #d32f2f;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-item.user .message-avatar {
  background: #fff;
  border: 2px solid #d32f2f;
  color: #d32f2f;
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.message-item.user .message-content {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message-text {
  background: #f5f5f5;
  padding: 12px 16px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  word-wrap: break-word;
  word-break: break-word;
  white-space: pre-wrap;
  max-width: 100%;
  overflow-wrap: break-word;
}

.message-item.user .message-text {
  background: #d32f2f;
  color: #fff;
}

.message-text :deep(ul),
.message-text :deep(ol) {
  margin: 8px 0;
  padding-left: 20px;
}

.message-text :deep(li) {
  margin: 4px 0;
  list-style-position: outside;
}

.message-text :deep(strong) {
  font-weight: bold;
  color: #d32f2f;
}

.message-text :deep(code) {
  background: rgba(0, 0, 0, 0.05);
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

.message-text :deep(pre) {
  background: #2d2d2d;
  color: #f8f8f2;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 8px 0;
}

.message-text :deep(pre code) {
  background: transparent;
  color: inherit;
  padding: 0;
}

.message-item.user .message-text :deep(code) {
  background: rgba(255, 255, 255, 0.2);
}

.message-item.user .message-text :deep(pre) {
  background: rgba(0, 0, 0, 0.2);
}

.message-item.user .message-text :deep(strong) {
  color: #fff;
  font-weight: bold;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.message-item.user .message-time {
  text-align: right;
}

/* 加载动画 */
.loading-text {
  display: flex;
  gap: 4px;
  padding: 12px 16px;
}

.dot {
  width: 8px;
  height: 8px;
  background: #999;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

/* 输入区域 */
.input-container {
  border-top: 1px solid #e0e0e0;
  padding: 16px 24px;
  background: #fafafa;
}

.input-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-tips {
  font-size: 12px;
  color: #999;
}

/* 快捷提问 */
.quick-questions {
  margin-top: 24px;
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.quick-questions h3 {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
}

.question-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 12px;
}

.question-card {
  padding: 12px 16px;
  background: #f5f5f5;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.question-card:hover {
  background: #fff;
  border-color: #d32f2f;
  color: #d32f2f;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(211, 47, 47, 0.1);
}

.question-card .el-icon {
  color: #d32f2f;
  font-size: 18px;
}

/* 动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-wrapper {
    flex-direction: column;
    height: auto;
  }

  .history-sidebar {
    width: 100%;
    height: 200px;
    margin-bottom: 16px;
  }

  .chat-container {
    height: calc(100vh - 350px);
  }

  .message-content {
    max-width: 80%;
  }

  .question-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 1024px) {
  .history-sidebar {
    width: 240px;
  }
}
</style>

